package com.h2o3.carmack.session;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.glassfish.grizzly.websockets.WebSocket;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.h2o3.carmack.message.Message;

/**
 * @author chensheng
 * @version $Id: SessionGroup.java, v 0.1 1/18/14 10:48 PM chensheng Exp $
 */
public class SessionGroup {
    private Map<String, Session> sessions = Maps.newConcurrentMap();
    private Set<WebSocket>       sockets  = Sets.newConcurrentHashSet();

    public void add(Session session) {
        sessions.put(session.getSessionKey(), session);
        sockets.add(session.getSocket());
    }

    public void remove(Session session) {
        sockets.remove(session.getSocket());
        sessions.remove(session.getSessionKey());
    }

    public Session get(String sessionKey) {
        return sessions.get(sessionKey);
    }

    public Collection<Session> find(Predicate<Session> predicate) {
        return Collections2.filter(sessions.values(), predicate);
    }

    protected void broadcast(Session session, Message message) {
        session.getSocket()
            .broadcast(sockets, session.getMessageSerializer().writeMessage(message));
    }
}